package com.example.administrator.listview_sqlite2;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ListView;

import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private ListView lvstu;
    private Button btnadd;
    private ArrayList<Student>studentArrayList=new ArrayList<Student>();
    private StuAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /*事件绑定*/
       findView();
        /*初始化学生列表*/
       // initStudentArrayList();
        /*从数据库中读取学生列表*/
        readDataFromDB();
        adapter=new StuAdapter(MainActivity.this,studentArrayList);
        lvstu.setAdapter(adapter);

    }

    private void readDataFromDB() {
        String path=getFilesDir().getAbsolutePath()+ File.separator+"stu.db";
        SQLiteDatabase db=SQLiteDatabase.openOrCreateDatabase(path,null);
        String sql="create table if not exists Student(stuno varchar(20),name varchar(20),age int)";
        db.execSQL(sql);
       Cursor cursor= db.query("student",null,null,
                    null,null,null,null);
       if (cursor==null||cursor.getCount()==0){
           return;
       }
       studentArrayList.clear();
       for (cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
           String no=cursor.getString(0);
           String name=cursor.getString(1);
           int age=cursor.getInt(2);
           Student student=new Student(no,name,age);
           studentArrayList.add(student);
       }
       cursor.close();
       db.close();
    }

    private void initStudentArrayList() {
        studentArrayList.add(new Student("171","lasa1",18));
        studentArrayList.add(new Student("172","lasa2",19));
        studentArrayList.add(new Student("173","lasa3",20));
        studentArrayList.add(new Student("174","lasa4",21));
        studentArrayList.add(new Student("175","lasa5",22));
    }

    private void findView() {
        lvstu=findViewById(R.id.lv_stu);
        btnadd=findViewById(R.id.add_btn);
    }
}
